/*
 * Copyright (c) 2021.
 * @User: XiaoZhenRS
 * @QQ: 1419158026
 * @Gitee: gitee.com/XiaoZhengRS
 * @GitHub: github.com/XiaoZhengRS
 */

package com.xiaozhengkeji.mcverifyplus.oauth;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.xiaozhengkeji.mcverifyplus.pojo.ResponseBean;
import com.xiaozhengkeji.mcverifyplus.pojo.type.ResCodeType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalException {


    // 在当前类每个方法进入之前触发的操作
    @ModelAttribute
    public void get(HttpServletRequest request) {

    }

    // 全局异常拦截（拦截项目中的所有异常）
    @ResponseBody
    @ExceptionHandler
    public ResponseBean handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        // 打印堆栈，以供调试
        System.out.println("全局异常---------------");
        e.printStackTrace();
        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            return new ResponseBean(ResCodeType.Error, "未登录", ee.getMessage(), 1);
        } else if (e instanceof NotRoleException) {
            NotRoleException ee = (NotRoleException) e;
            return new ResponseBean(ResCodeType.Error, "无此角色", ee.getRole(), 2);
        } else if (e instanceof NotPermissionException) {
            NotPermissionException ee = (NotPermissionException) e;
            return new ResponseBean(ResCodeType.Error, "无此权限", ee.getCode(), 3);
        } else {    // 普通异常, 输出：500 + 异常信息
            return new ResponseBean(ResCodeType.Error, "服务器出错", e.getMessage(), 4);
        }
    }
}
